package com.fjb.controller.login;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjb.common.entity.HttpCode;
import com.fjb.common.entity.JsonResult;
import com.fjb.common.enums.user.RegisterSource;
import com.fjb.common.enums.user.UserStatus;
import com.fjb.common.enums.user.UserType;
import com.fjb.controller.base.BaseController;
import com.fjb.dto.LoginUserInfo;
import com.fjb.pojo.login.SysLoginToken;
import com.fjb.pojo.user.SysUser;
import com.fjb.service.login.SysLoginTokenService;
import com.fjb.service.user.SysUserService;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;

/**
 * @Description:登陆
 * @author hemiao
 * @time:2020年1月30日 下午8:32:40
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
    private WxMaService wxService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysLoginTokenService sysLoginTokenService;
	
	/**
	 * @Description:微信登陆授权
	 * @param request
	 * @return
	 * JsonResult<Object>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年1月30日 下午8:34:13
	 */
	@RequestMapping(value="/wxAuth")
	@ResponseBody
	public JsonResult<Object> wxAuth(HttpServletRequest request){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		String code = request.getParameter("code");
		if(StringUtils.isBlank(code)) {
			httpCode.setMsg("微信code不能为空");
			return new JsonResult<Object>(null, httpCode);
		}
		String userInfoStr = request.getParameter("userInfo");
		if(StringUtils.isBlank(userInfoStr)) {
			httpCode.setMsg("微信code不能为空");
			return new JsonResult<Object>(null, httpCode);
		}
		LoginUserInfo userInfo = JSON.parseObject(userInfoStr, LoginUserInfo.class);
		String wxOpenId = null;
		String sessionKey = null;
		try {		
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            logger.info(" wx登陆  result = "+JSON.toJSON(result));
            sessionKey = result.getSessionKey();
            wxOpenId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }
		if (sessionKey == null || wxOpenId == null) {
			httpCode.setMsg("微信授权失败");
            return new JsonResult<Object>(null, httpCode);
        }
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
		queryWrapper.eq("wx_open_id", wxOpenId);
		SysUser user = sysUserService.getOne(queryWrapper);
		if(user==null) {
			LocalDateTime localDateTime = LocalDateTime.now();
			// 新用户	
			user = new SysUser();
			user.setMainUserId(0);
			user.setNickname(userInfo.getNickName());
			Byte gender = userInfo.getGender();
			if(gender!=null) {
				if(gender==1) {	
					user.setGender("男");
				}else {
					user.setGender("女");
				}
			}		
			user.setWxOpenId(wxOpenId);
			user.setWxSessionKey(sessionKey);
			user.setUserStatus(UserStatus.STATUS_1.getCode());
			user.setUserType(UserType.TYPE_1002.getCode());
			user.setRegisterSource(RegisterSource.WX_APPLET.getCode());
			user.setCreateTime(localDateTime);
			// 微信注册
			user = sysUserService.addWxAuth(user);
		}else {
			LocalDateTime localDateTime = LocalDateTime.now();
			// 老用户		
			user.setUpdateTime(localDateTime);
			sysUserService.updateById(user);
		}	
		// 手机号
		String phone = user.getPhone();
		if(StringUtils.isNotBlank(phone)) {
			userInfo.setPhone(phone);
		}else {	
			userInfo.setPhone("");
		}
		String province = user.getProvince();
		if(StringUtils.isNotBlank(province)) {
			userInfo.setProvince(province);
		}else {
			userInfo.setProvince("");
		}
		String city = user.getCity();
		if(StringUtils.isNotBlank(city)) {
			userInfo.setCity(city);
		}else {
			userInfo.setCity("");
		}	
		String district = user.getDistrict();
		if(StringUtils.isNotBlank(district)) {
			userInfo.setDistrict(district);
		}else {
			userInfo.setDistrict("");
		}
		String address = user.getAddress();
		if(StringUtils.isNotBlank(address)) {
			userInfo.setAddress(address);
		}else {
			userInfo.setAddress("");
		}
		BigDecimal latitude = user.getLatitude();
		if(latitude!=null) {
			userInfo.setLatitude(latitude);
		}
		BigDecimal longitude = user.getLongitude();
		if(longitude!=null) {
			userInfo.setLongitude(longitude);
		}
		
		Integer userId = user.getId();
		Integer mainUserId = user.getMainUserId();
		userInfo.setUserId(userId);
		userInfo.setMainUserId(mainUserId);
		String tokenId = setBaseWxTokenId(request,wxOpenId, userInfo);
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", tokenId);	
        result.put("userInfo", userInfo);	
		return new JsonResult<Object>(result, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:手机号登陆
	 * @param request
	 * @return
	 * JsonResult<Object>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年1月30日 下午8:34:39
	 */
	@RequestMapping(value="/phoneAuth")
	@ResponseBody
	public JsonResult<Object> phoneAuth(HttpServletRequest request){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		String phone = request.getParameter("phone");
		if(StringUtils.isBlank(phone)) {
			httpCode.setMsg("手机号不能为空");
			return new JsonResult<Object>(null, httpCode);
		}
		
		
		
		return new JsonResult<Object>(null, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:退出登陆	logout
	 * @param request
	 * void
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月19日 下午9:06:14
	 */
	@RequestMapping(value="/logout")
	@ResponseBody
	public void logout(HttpServletRequest request){
		String appToken = request.getHeader(WX_TOKEN_ID);
		StringJoiner sj = new StringJoiner(":");
		sj.add(WX_TOKEN_ID);
		sj.add(appToken);
		String token = sj.toString();
		// 存redis
		//redisTemplate.opsForValue().set(token, jsonStr,60*10*6*24*15,TimeUnit.SECONDS);
		// 存数据库	
		// 先删除		
		QueryWrapper<SysLoginToken> queryWrapper = new QueryWrapper<SysLoginToken>();
		queryWrapper.eq("token_id", token);
		sysLoginTokenService.remove(queryWrapper);
		logger.info(" 退出登陆 : "+token);
	}
}
